const {getclasshourData} = require("../utils/misc")
const ObjectId = require('mongodb').ObjectId
const router = require('koa-router')();
const mongo = require('../compents/mongo')
const {postLogData} =require("../utils/misc")
router.prefix('/classhour')

router.get('/list', async ctx => {
    postLogData("请求课时")
    let { page} = ctx.query
    const res = await mongo.find('classhour', {page:page*1})
    const total = res.length
    if (res) {
        ctx.body = { data: res, code: 20000, total, message: "数据请求成功" }
    } else {
        ctx.body = {data:res, code: 50001, message: "数据请求失败" }
    }
})

router.post('/save', async ctx => {
    postLogData("新增课时")
    let camData = ctx.request.body
    const orders =await getclasshourData()
    const res = await mongo.insertOne('classhour', { ...camData,orders:orders+1})
    if (res.insertedId) {
        ctx.body = { data: res, code: 20000, message: "数据插入成功" };
    } else {
        ctx.body = { data: res, code: 50002, message: "数据插入失败" };
    }
})

// 删除单挑数据
router.get('/delOne', async ctx => {
    postLogData("单删课时")
    const { _id } = ctx.query
    const res = await mongo.deleteOne('classhour', { _id: ObjectId(_id) })
    if (res.deletedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据删除成功" };
    } else {
        ctx.body = { data: res, code: 50005, message: "数据删除失败" };
    }
})

module.exports = router 